/*
 * @Author: fuzhuang
 * @Date: 2023-12-11 09:23:21
 * @LastEditTime: 2023-12-11 09:53:35
 * @LastEditors: fuzhuang
 * @Description:
 * @FilePath: \golib\easyjson\json.go
 */
/*
 * @Author: Wangjun
 * @Date: 2021-12-10 10:47:47
 * @LastEditTime: 2023-10-13 15:57:00
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \xr_node_calcd:\go\src\gitee.com\haodreams\golib\easyjson\json.go
 * hnxr
 */

package easyjson

//-tags=jsoniter
import (
	"math"
	"strconv"
	"time"
	"unsafe"

	"gitee.com/haodreams/libs/easy"
	jsoniter "github.com/json-iterator/go"
)

// 浮点型数据的精度
var defaultPrecision = 3
var defaultTimeFmt = easy.YYYYMMDDHHMMSS

/**
 * @description: 设置默认的精度
 * @param {int} prec
 * @return {*}
 */
func SetDefaultPrecision(prec int) {
	defaultPrecision = prec
}

/**
 * @description: 设置默认的时间格式
 * @param {string} fmt
 * @return {*}
 */
func SetDefaultTimeFormat(fmt string) {
	defaultTimeFmt = fmt
}

/**
 * @description: float 转字符串
 * @param {float64} f
 * @param {int} prec -1 保留全部的精度
 * @return {*}
 */
func FloatToString(f float64, prec int) (fs string) {
	if math.IsNaN(f) || math.IsInf(f, 0) {
		fs = "null"
	} else {
		num := f - float64(int64(f))
		if math.Abs(num) < 0.000001 {
			fs = strconv.FormatInt(int64(f), 10)
		} else {
			fs = strconv.FormatFloat(f, 'f', prec, 64)
		}
	}
	return
}

func Default() {
	jsoniter.RegisterTypeEncoderFunc("float64", func(ptr unsafe.Pointer, stream *jsoniter.Stream) {
		f := *((*float64)(ptr))
		stream.WriteRaw(FloatToString(f, defaultPrecision))
	}, nil)

	jsoniter.RegisterTypeEncoderFunc("float32", func(ptr unsafe.Pointer, stream *jsoniter.Stream) {
		f := *((*float32)(ptr))
		stream.WriteRaw(FloatToString(float64(f), defaultPrecision))
	}, nil)

}

func DefaultTime() {
	jsoniter.RegisterTypeDecoderFunc("time.Time", func(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
		s := iter.ReadString()
		if iter.Error != nil {
			return
		}
		t, err := time.ParseInLocation(easy.YYYYMMDDHHMMSS, s, time.Local)
		if err != nil {
			iter.Error = err
			return
		}
		*((*time.Time)(ptr)) = t
	})

	jsoniter.RegisterTypeEncoderFunc("time.Time", func(ptr unsafe.Pointer, stream *jsoniter.Stream) {
		f := *((*time.Time)(ptr))
		stream.WriteString(f.Format(defaultTimeFmt))
	}, nil)

}
